package com.controller;

import com.entry.*;
import com.server.AddressService;
import com.server.OrderFormService;
import com.server.ProductcollectService;
import com.server.ShoppingService;
import com.server.impl.MemberServiceImpl;
import com.server.impl.ProductServiceImpl;
import com.util.RedisUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class MemberController {//处理用户相关的请求
    @Resource
    MemberServiceImpl memberService;
    @Resource
    ProductServiceImpl productService;
    @Autowired
    RedisUtil redisUtil;
    @Resource
    ShoppingService shoppingService;
    @Resource
    AddressService addressService;
    @Resource
    OrderFormService orderFormService;
    @Resource
    ProductcollectService productcollectService;

    //登录
    @RequestMapping(value = "/member/login",method = RequestMethod.GET)
    @ResponseBody
    public Result login(String member_name, String member_pwd, Model model, HttpSession session){
        Result result = new Result();
        //调用业务逻辑层根据用户名和密码查询用户是否存在，返回user对象，
        // 如果不为空，可以登录否则，重新登录
        Member member =memberService.getLoginMember(member_name,member_pwd);
        if (member !=null){
            //把user对象保存到model中
            session.setAttribute("member_name",member_name);
            session.setAttribute("member",member);
            //把用户存入缓存
            redisUtil.set("member_name",member_name);
            redisUtil.set("member", String.valueOf(member));
            redisUtil.set("member_id", String.valueOf(member.getMember_id()));
            redisUtil.set("member_address", String.valueOf(member.getMember_address()));

            int countShopping=shoppingService.getCount(member.getMember_id());
            session.setAttribute("countShopping",countShopping);

            List<Product> productListimgandproduct=productService.getproducandproductimageList();
            model.addAttribute("productListimgandproduct",productListimgandproduct);
            System.out.println(redisUtil.get("member_name"));

            int user_id=member.getMember_id();
            List<OrderForm> orderFormList=orderFormService.getOrderSellandStatus(user_id, 0);
            redisUtil.set("daifahuo", String.valueOf(orderFormList.size()));
            session.setAttribute("daifahuo", String.valueOf(orderFormList.size()));

            List<OrderForm> orderFormList1=orderFormService.getOrderSellandStatus(user_id, 1);
            redisUtil.set("daishouhuo", String.valueOf(orderFormList1.size()));
            session.setAttribute("daishouhuo", String.valueOf(orderFormList1.size()));

            result.setSuccess(true);
            return result;
        }else {
            result.setSuccess(false);
            return result;
        }
    }


    //处理添加用户的请求
    @RequestMapping(value = "/member/doregister",method = RequestMethod.POST)
    @ResponseBody
    public Result doregister(String member_name,String member_nickname,
                             String member_phone,String member_pwd,String member_gender,
                             String member_address,String member_email, Model model) {

        Result result = new Result();

        System.out.println("member_name="+member_name);

        int num=memberService.getMemberByMemberName(member_name);
        if (num>0){
            result.setSuccess(false);
            return result;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date(System.currentTimeMillis());
        System.out.println("当前日期时间为：" + formatter.format(d));
        int count=memberService.getRegisterMemberDate(member_name, member_nickname, member_pwd, member_gender, member_address, member_phone, d,member_email);

        if(count>0){
            result.setSuccess(true);
            return result;
        }
        result.setSuccess(false);
        return result;
    }

    //请求到car界面
    @RequestMapping("/member/getcart")
    public String getcart(HttpSession session){
        int member_id=Integer.parseInt(String.valueOf(redisUtil.get("member_id")));
        List<Shopping> shoppingList= shoppingService.getShoppingList(member_id);

        int countShopping=shoppingService.getCount(member_id);
        session.setAttribute("countShopping",countShopping);

        shoppingList.forEach(System.out::println);
        session.setAttribute("shoppingList",shoppingList);
        return "cart";
    }

    //请求到list界面
    @RequestMapping("/member/getlist")
    public String getlist(){

        return "list";
    }
    //请求到collect界面
    @RequestMapping("/member/getcollect")
    public String getcollect(HttpSession session){
        String member_id=String.valueOf(redisUtil.get("member_id"));
        int productcollect_member_id = Integer.parseInt(member_id);
        //判断缓存是否有用户的member_id
        if (member_id!=null){
            List<Productcollect> productcollectList =productcollectService.getAllProductCollect(productcollect_member_id);
            session.setAttribute("productcollectList",productcollectList);
        }
        return "collect";
    }
    //请求到pay界面
    @RequestMapping("/member/getpay")
    public String getpay(){
        return "pay";
    }
    //请求到register界面
    @RequestMapping("/member/getregister")
    public String getregister(){
        return "register";
    }
/*
    //请求到register界面
    @RequestMapping("/member/getregister")
    public String getregister(Map<String,Object> map){
        String addressId = "110000";//默认
        String cityAddressId = "110100";//默认
        System.out.println("获取省份信息");
        List<Address> addressList = addressService.getRoot();
        System.out.println("获取addressId为{}的市级地址信息"+addressId);
        List<Address> cityAddress = addressService.getList(null, addressId);
        System.out.println("获取cityAddressId为{}的区级地址信息"+cityAddressId);
        List<Address> districtAddress = addressService.getList(null, cityAddressId);
        map.put("addressList", addressList);
        map.put("cityList", cityAddress);
        map.put("districtList", districtAddress);
        map.put("addressId", addressId);
        map.put("cityAddressId", cityAddressId);
        System.out.println("转到用户注册页");
        return "register";
    }
*/
    //请求到register界面
    @RequestMapping("/getregister")
    public String getregister1(){

        return "register";
    }
/*
    //请求到register界面
    @RequestMapping("/getregister")
    public String getregister1(Map<String,Object> map){

        String addressId = "110000";//默认
        String cityAddressId = "110100";//默认
        System.out.println("获取省份信息");
        List<Address> addressList = addressService.getRoot();
        System.out.println("获取addressId为{}的市级地址信息"+addressId);
        List<Address> cityAddress = addressService.getList(null, addressId);
        System.out.println("获取cityAddressId为{}的区级地址信息"+cityAddressId);
        List<Address> districtAddress = addressService.getList(null, cityAddressId);
        map.put("addressList", addressList);
        map.put("cityList", cityAddress);
        map.put("districtList", districtAddress);
        map.put("addressId", addressId);
        map.put("cityAddressId", cityAddressId);
        System.out.println("转到用户注册页");
        return "register";
    }
*/
    //请求到index界面
    @RequestMapping("/member/getindex")
    public String getindex(Model model){
        List<Product> productListimgandproduct=productService.getproducandproductimageList();
        model.addAttribute("productListimgandproduct",productListimgandproduct);
        return "index";
    }
    //请求到login界面
    @RequestMapping("/member/getlogin")
    public String getlogin(){
        return "login";
    }

    //请求到login界面，退出登录
    @RequestMapping("/member/getloglogin")
    public String getloglogin(HttpSession session){
        session.invalidate();
        return "index";
    }
    //请求到login界面
    @RequestMapping("/getlogin")
    public String getlogin1(HttpSession session){

        String member_id=String.valueOf(redisUtil.get("member_id"));
        if (member_id!=null){
            List<OrderForm> orderFormList=orderFormService.getOrderSell(Integer.parseInt(member_id));
            session.setAttribute("orderFormList",orderFormList);
        }
        return "login";
    }
    //请求到userdetail界面
    @RequestMapping("/member/getuserdetail")
    public String getuserdetail(HttpSession session){
        String member_id=String.valueOf(redisUtil.get("member_id"));
        if (member_id!=null){
            List<OrderForm> orderFormList=orderFormService.getOrderSell(Integer.parseInt(member_id));
            session.setAttribute("orderFormList",orderFormList);
        }
        return "userdetail";
    }
    //请求到userdetail界面
    @RequestMapping("/getpassword")
    public String getpassword(){

        return "password";
    }

    @Resource
    JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean
    //用邮箱找回密码
    @RequestMapping(value = "/member/sendMail",method = RequestMethod.POST)
    @ResponseBody
    public Map sendMail(String email){
        Map<String,String> result=new HashMap<>();
        System.out.println(email);
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();

        //查找是否含有邮箱号
        List<Member> memberList=memberService.getEmailMember(email);
        if (memberList.size()<1){
            result.put("msg","fail");
            return result;
        }else {
            try {
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
                //发件人的邮箱地址
                messageHelper.setFrom("V17695662538@126.com");//发件人
                // 收件人的邮箱地址
                messageHelper.setTo(email);//收件人
                messageHelper.setSubject("主题：找回密码提醒");
                int Password = ((int)((Math.random()*9+1)*100000));//产生随机的6位数密码
                messageHelper.setText("xxx提醒，您的密码为："+ Password,true);//true代表支持html格式
                System.out.println(mimeMessage);
                System.out.println(messageHelper);
                javaMailSender.send(mimeMessage);
                //修改数据库中的密码
                memberService.modifyPasswordByEmail(String.valueOf(Password), email);
                result.put("msg","success");
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }

        return result;
    }


}
